package com.aleyn.router.executor

import com.aleyn.router.util.dLog
import java.util.concurrent.ThreadFactory
import java.util.concurrent.atomic.AtomicInteger

/**
 * @author: Aleyn
 * @date: 2023/7/10 16:35
 *
 * LRouter 框架的默认线程工厂。
 * 用于创建具有统一命名规范和异常处理的线程。
 */
internal class DefaultThreadFactory : ThreadFactory {

    // 线程池编号
    private val poolNumber = AtomicInteger(1)

    // 线程编号
    private val threadNumber = AtomicInteger(1)

    // 线程名称前缀
    private val namePrefix: String

    // 线程组
    private val group: ThreadGroup?

    // 未捕获异常处理器
    private val exceptionHandler = Thread.UncaughtExceptionHandler { t, ex ->
        "Running task appeared exception! Thread [" + t.name + "], because [" + ex.message + "]".dLog()
    }

    init {
        val s = System.getSecurityManager()
        group = if (s != null) s.threadGroup else Thread.currentThread().threadGroup
        namePrefix = "LRouter task pool No.${poolNumber.getAndIncrement()}, thread No."
    }

    /**
     * 创建一个新线程。
     *
     * @param runnable 要在新线程中执行的任务。
     * @return 创建的线程。
     */
    override fun newThread(runnable: Runnable): Thread {
        val threadName = namePrefix + threadNumber.getAndIncrement()
        "Thread production, name is [$threadName]".dLog()
        return Thread(group, runnable, threadName, 0).apply {
            // 确保线程不是守护线程
            if (isDaemon) isDaemon = false
            // 设置为正常优先级
            if (priority != Thread.NORM_PRIORITY) priority = Thread.NORM_PRIORITY
            // 设置未捕获异常处理器
            uncaughtExceptionHandler = exceptionHandler
        }
    }

}